package com.example.carbonbackend.service.impl;

import com.example.carbonbackend.model.dto.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 读取Word文件
 */
@Service
public class WordReader {
    /**
     * 读取word文件中的数据
     */
    public static List<String> eGwordReader(File wordFile) throws IOException {
        int columnIndex = 2;
        List<String> columnData = new ArrayList<>();

        FileInputStream fis = new FileInputStream(wordFile);
        XWPFDocument document = new XWPFDocument(fis);

        // 1.获取文档中的第一个表格
        List<XWPFTable> tables = document.getTables();
        if (!tables.isEmpty()) {
            XWPFTable table = tables.get(0); // 第一个表格

            // 2.遍历表格的每一行
            for (int i = 0; i < table.getNumberOfRows(); i++) {
                XWPFTableRow row = table.getRow(i);
                // 3.获取指定列的单元格数据
                if (row.getTableCells().size() > columnIndex) {
                    XWPFTableCell cell = row.getCell(columnIndex);
                    String cellText = cell.getText();
                    // 4.去除首尾空白字符并添加到列数据列表中
                    columnData.add(cellText.trim());
                } else {
                    // 5.如果列数不够，返回格式错误
                    throw new IllegalStateException("表格格式错误");
                }
            }
        }

        if (tables.size() > 1) {
            XWPFTable secondTable = tables.get(1);
            if (secondTable.getNumberOfRows() > 1) {
                XWPFTableRow secondRow = secondTable.getRow(1);
                if (secondRow.getTableCells().size() > 2) {
                    XWPFTableCell secondCell = secondRow.getCell(2);
                    String cellText = secondCell.getText();

                    columnData.add(cellText);
                } else {
                    // 6.如果列数不够，返回格式错误
                    throw new IllegalStateException("表格格式错误");
                }
            }
        }

        return columnData;
    }

    /**
     * 处理读取过的word文件的数据
     */
    public static EGCarbonemissionDto eGAssignment(String name, String year, File wordFile) throws IOException {
        try {
            List<String> columnData = eGwordReader(wordFile);
            EGCarbonemissionDto egCarbonemission = new EGCarbonemissionDto();
            egCarbonemission.setEFE(Double.parseDouble(columnData.get(23)));

            List<Double> firstSet = new ArrayList<>();
            List<Double> secondSet = new ArrayList<>();
            Double thirdValue = null;


            //1.燃烧化石燃料（包括发电及其他排放源使用化石燃料）产生的二氧化碳排放量（吨）

            for (int i = 1; i <= 10; i++) {
                String data = columnData.get(i);
                if (data != null && !data.isEmpty()) {
                    System.out.println(data);
                    firstSet.add(Double.parseDouble(data));
                }
            }

            System.out.println("------------------");

            // 2.脱硫过程产生的二氧化碳排放量

            for (int i = 12; i <= 20; i++) {
                String data = columnData.get(i);
                if (data != null && !data.isEmpty()) {
                    System.out.println(data);
                    secondSet.add(Double.parseDouble(data));
                }
            }

            //3.读取净购入使用电力产生的二氧化碳排放量
            String data = columnData.get(22);
            if (data != null && !data.isEmpty()) {
                System.out.println(data);
                thirdValue = Double.parseDouble(data);
            }


            egCarbonemission.setYear(year);
            egCarbonemission.setCompanyName(name);
            List<FossilFuelDto> fossilFuelList = egCarbonemission.getFossilFuelList();
            for (int i = 0; i < fossilFuelList.size(); i++) {
                FossilFuelDto fossilFuel = fossilFuelList.get(i);
                fossilFuel.setFC(firstSet.get(i));
            }
            List<DesulfurizerDto> desulfurizerList = egCarbonemission.getDesulfurizerList();
            for (int i = 0; i < desulfurizerList.size(); i++) {
                DesulfurizerDto desulfurizerDto = desulfurizerList.get(i);
                desulfurizerDto.setI(secondSet.get(i));
            }

            egCarbonemission.setADE(thirdValue);
            return egCarbonemission;
        } catch (IllegalStateException e) {
            throw e;
        }

    }

    public static EUCarbonemissionDto eUAssignment(String name, String year, File wordFile) throws IOException {
        EUCarbonemissionDto euCarbonemissionDto=new EUCarbonemissionDto();
        euCarbonemissionDto.setCompanyName(name);
        euCarbonemissionDto.setYear(year);
        List<RepairEquipmentDto> repairEquipment=new ArrayList<>();
        List<RetiredEquipmentDto> retiredEquipment=new ArrayList<>();
        List<String> FileData= eUwordReader(wordFile);
        for (int i = 1; i < FileData.size()-6; i++) {
            RetiredEquipmentDto retiredEquipmentDto = new RetiredEquipmentDto();
            RepairEquipmentDto repairEquipmentDto = new RepairEquipmentDto();
            Double data0=Double.parseDouble(FileData.get(i-1));
            Double data=Double.parseDouble(FileData.get(i));
            if(i%4==1){
                repairEquipmentDto.setCapacity(data0);
                repairEquipmentDto.setRecovery(data);
                repairEquipment.add(repairEquipmentDto);
                System.out.println(repairEquipmentDto.getCapacity());
                System.out.println(repairEquipmentDto.getRecovery());
            } else if(i%4==3){
                retiredEquipmentDto.setCapacity(data0);
                retiredEquipmentDto.setRecovery(data);
                retiredEquipment.add(retiredEquipmentDto);
            }
        }
        for(int i=FileData.size()-6;i< FileData.size()-1;i++){

        }
        euCarbonemissionDto.setELSurf(Double.parseDouble(FileData.get(FileData.size()-6)));
        euCarbonemissionDto.setELIn(Double.parseDouble(FileData.get(FileData.size()-5)));
        euCarbonemissionDto.setELOut(Double.parseDouble(FileData.get(FileData.size()-4)));
        euCarbonemissionDto.setELSell(Double.parseDouble(FileData.get(FileData.size()-3)));
        euCarbonemissionDto.setRepairList(repairEquipment);
        euCarbonemissionDto.setRetireList(retiredEquipment);

        Double eF=Double.parseDouble(FileData.get(FileData.size()-1));
        euCarbonemissionDto.setEF(eF);
        return euCarbonemissionDto;
    }

    public static List<String> eUwordReader(File wordFile) throws IOException {
        List<String> dataRows = new ArrayList<>();
        try {
            FileInputStream fis = new FileInputStream(wordFile);
            XWPFDocument document = new XWPFDocument(fis);

            // Assuming the first table in the document
            XWPFTable table = document.getTables().get(0);

            // Rows 3 to 12
            for (int i = 2; i < 12; i++) {
                XWPFTableRow row = table.getRow(i);
              //  String[] rowData = new String[4];
                // Columns 2, 3, 5, 6
                for (int j = 1; j < 6; j++) {
                    if(j==3) continue;
                    XWPFTableCell cell = row.getCell(j);
                    dataRows.add(cell.getText().isEmpty() ? "0" : cell.getText());
                }
            }

            // Rows 14 to 18
         //   List<String> additionalRows = new ArrayList<>();
            for (int i = 13; i < 18; i++) {
                XWPFTableRow row = table.getRow(i);
                XWPFTableCell cell = row.getCell(1); // Second column
                dataRows.add(cell.getText().isEmpty() ? "0" : cell.getText());
            }

            // Print the data


            XWPFTable table1 = document.getTables().get(1);

            XWPFTableRow row = table1.getRow(1);
            XWPFTableCell cell = row.getCell(2);
            String cellContent = cell.getText();
            dataRows.add(cellContent);
            for (int i = 0; i < dataRows.size(); i++) {
                //System.out.println(dataRows.get(i));
            }
            System.out.println(cellContent);
            fis.close();
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return dataRows;
    }

}

